from app01 import models
import hashlib
from rest_framework.response import Response
import random


# Create your views here.

def auth_token(func):
    def wrapper(*args, **kwargs):
        request = args[1]
        token = request.META.get('HTTP_TOKEN')
        if not models.Token.objects.filter(token=token):
            print('该账号没登录')
            return Response({'code': '300', 'err': '该账号尚未登录'})
        return func(*args, **kwargs)
    return wrapper


class TokenFun(object):
    def __init__(self, user_obj):
        self.obj = user_obj

    def logout(self):
        if models.Token.objects.filter(user=self.obj):
            models.Token.objects.filter(user=self.obj).delete()

    def login(self):
        data = self.obj.username + str(random.randint(1000, 10000))
        token = hashlib.md5(data.encode('utf-8')).hexdigest()
        if models.Token.objects.filter(user=self.obj):
            models.Token.objects.filter(user=self.obj).update(token=token)
        else:
            models.Token.objects.create(token=token, user=self.obj)
        return token


def get_code(order_id):
    order_id = str(order_id) + str(random.randint(1000, 10000))
    code_number = hashlib.md5(order_id.encode('utf-8')).hexdigest()
    return code_number